package com.nancal.activiti.service.impl;

import com.nancal.activiti.service.FileManageService;
import com.nancal.activiti.service.ModelImageService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.UUID;

@Service
public class FileManageServiceImpl implements FileManageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileManageService.class);
    @Value("${file_hostpath}")
    private String fileHostPath;
    @Autowired
    ModelImageService modelImageService;
    @Autowired
    HistoryService historyService;
    @Autowired
    RepositoryService repositoryService;

    @Override
    public String upload(MultipartFile file) {
        File test = new File(fileHostPath+"/"+file.getOriginalFilename());
        if (!test.exists()){
            test.mkdirs();
        }
        try {
            file.transferTo(test);
        }catch (IOException e){
            LOGGER.error(file.getOriginalFilename()+"文件上传失败", e);
        }

        return "文件上传成功";
    }

    @Override
    public String upload(MultipartFile file,String modelId) {
        String comFileName=file.getOriginalFilename();
        String preFileName = comFileName.substring(0, comFileName.lastIndexOf("."));
        String lastFileName = comFileName.substring(comFileName.lastIndexOf("."),comFileName.length());

        String fileName = preFileName+UUID.randomUUID().toString()+lastFileName;

        File test = new File(fileHostPath+"/"+fileName);
        if (!test.exists()){
            test.mkdirs();
        }
        try {
            file.transferTo(test);
        }catch (IOException e){
            LOGGER.error(file.getOriginalFilename()+"文件上传失败", e);
        }
        modelImageService.addFileByModelId(fileName,modelId);
        return "文件上传成功";
    }

    @Override
    public String download(String deploymentId, HttpServletResponse response){

        Model model = repositoryService.createModelQuery().deploymentId(deploymentId).singleResult();
        String fileName=modelImageService.findFileBymodelId(model.getId());
        if (Objects.isNull(fileName)) {
            return "文件下载失败，请选择文件要下载的文件";
        }
        File file = new File(fileHostPath +"/"+ fileName);
        if (!file.exists()){
            return "文件不存在";
        }
        byte[] bytes = new byte[2048];
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);

            response.setHeader("content-type", "application/octet-stream");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            int length;
            while ((length = bufferedInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, length);
            }
            outputStream.flush();
        }catch (Exception e){
            LOGGER.error("文件下载失败", e);
        }finally {
            try {
                if (bufferedInputStream != null){
                    bufferedInputStream.close();
                }

                if (outputStream != null){
                    outputStream.close();
                }

                if (fileInputStream != null){
                    fileInputStream.close();
                }
            }catch (IOException e){
                LOGGER.error(e.getMessage(), e);
            }
        }
        return "success";
    }

}
